package com.ktjy.t382.ch01.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

public class HelloFilter implements Filter {
    //filter 初始化
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Filter init");
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("doFilter...执行前");
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        Object object = httpServletRequest.getSession().getAttribute("session_user");
        if (object == null) {
            HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
            httpServletResponse.sendRedirect("error.jsp");
        }
        filterChain.doFilter(servletRequest, servletResponse);
//        HelloServlet helloServlet = new HelloServlet();
//        helloServlet.doGet(servletRequest, servletResponse);
        System.out.println("doFilter...执行后");
    }

    //销毁
    @Override
    public void destroy() {
        System.out.println("Filter destroy");
        Filter.super.destroy();
    }
}
